define(function(require,exports,module) {
    var myPub = require('./public');
    var GoodsSizeEvent = require('./goodsSize_selet');
    // 曝光可视区域元素
    var visualArea = require('./visualAreaInfo');


    if($('#js_videoPlay').length > 0) {
        var myVideoPlay = require('./videoConfig');
        myVideoPlay.videoSet('js_videoPlay');
    }

    var oWindow = $(window);
    var oWrap = $('.js_wrap');                      // wrap 部分
    var oContain = $('.js_contain');                // 页面内容区域
    var oFooter = $('.js_footer');                  //底部

    var oShadow = $('.js_shadow');				    //阴影
    var oServerMain = $('.js_serverMain');		    //服务说明内容
    var oServerList = $('.js_serverList');		    //产品服务信息列表
    var oServer_button = $('.js_server_button');    //服务说明确定按钮

    var otextureMain = $('.js_textureMain');             //口感评价
    var otexture = $('.js_texture');                     //口感评价页面点击对象
    var otextureButton = $('.js_textureButton');         //口感评价页面点击对象

    var otasteMain = $('.js_tasteMain');              //试吃列表
    var otastelist = $('.js_taste_report');          //详情页面点击对象
    var otasteButton = $('.js_tasteButton');          //试吃页面点击对象

    //var ocoverageMain = $('.js_coverageMain');              //全赔列表
   // var ocoveragelist = $('.js_taste_coverageList');          //页面全赔点击对象
    //var ocoverageButton = $('.js_coverage_button');          //全赔页面点击对象


    var osellMain = $('.js_sellMain');               //平台卖点列表
    var oselllist = $('.js_platform_advantage');     //详情页面点击对象
    var osellButton = $('.js_sellButton');          //平台卖点点击对象

    var oGoTop = $('.js_goTop');                    // 回到顶部
    var oEstimateList = $('.js_estimateList');      // 评价

    var oContactBossBtn = $('.js_contactBoss');     // 联系商家信息按钮 js_contactBoss
    var oBossInfo = $('.js_bossInfo');              // 商家信息 js_bossInfo
    var oBossName = $('.js_bossName');              // 店家名字

    var oGoodsHScroll = $('.js_goods_HScroll');

    var time_Scroll = null;

    var oSideBox = $('.js_sideBox');		        // 侧边按钮框
    var oSildeNavUl = $('.js_sildeNavUl ');
    var oSildeNavUl_Top = oSildeNavUl.offset().top;


    // 送礼功能
    var oGiftSendBtn = $('.js_giftSendBtn');                    // 送TA 按钮
    var oGiftSend_TypeSelet = $('.js_giftSend_TypeSelet');      // 送礼方式弹层
    var oTypeSeletList = $('.js_typeSeletList');                // 送礼方式选择
    var oTypeSeletIntro_layer = $('.js_typeSeletIntro_layer');  // 送礼方式说明
    var oTypeSelet_intro = $('.js_typeSelet_intro');            // 送礼方式说明按钮
    var oTypeSelelt_close = $('.js_typeSelelt_close');          // 送礼弹层关闭按钮
    var oGift_tip = $('.js_gift_tip');                          // 送礼弹层关闭按钮
    var oClose_giftTip = $('.js_close_giftTip');                // 送礼弹层关闭按钮
    var oPaginPacking = $('.js_paginPacking');                  //
    var showGiftTipOff = null;
    var storeDetailUrl = '/m/g/supplier/1.0/isOverSeaSupplier'; // 判断是进入海外店铺还是进入普通店铺的接口


    //取消滑动
    oFooter.on("touchmove",function(e) {e.preventDefault()});
    oShadow.on("touchmove",function(e) {e.preventDefault()});

    module.exports={
        init:function (data,names) {
            sfddjgooddetail.SetAdsLiScroll();
            sfddjgooddetail.ChangImgSize();
            sfddjgooddetail.SetServeSwiper(names);
            sfddjgooddetail.GiftTipShow();
            sfddjgooddetail.adsPackSwiper();

            // 限时秒杀
            limitTimeSale.CutDataTime();
            limitTimeSale.ProgressBar();

            oWindow.resize(function() {
                sfddjgooddetail.ChangImgSize();
            });

            oWindow.on('scroll', function () {
                myPub.throttle(scrollViewGoods, window);
            });

        }
    }

     var sfddjgooddetail = {
        packingSwiper:null,

         // 设置滚动广告
         SetAdsLiScroll: function () {
             var oHScrollBox = $('.js_HScroll');
             var oSlideAdsScroll = [];

             oHScrollBox.each(function (i) {
                 oSlideAdsScroll[i] = oHScrollBox.eq(i).swiper({
                     freeMode: true,
                     freeModeMomentumRatio: 0.5,
                     lazyLoading: true,
                     watchSlidesProgress: true,
                     watchSlidesVisibility: true,
                     slideClass: 'slide-HScroll',
                     slidesPerView: 'auto',
                     observer: true,
                     observeParents: true,
                     onSlideChangeEnd: function (swiper) {
                         var index = swiper.activeIndex;
                         ddjAction.viewGoods(oGoodsHScroll.eq(i), i);
                     }

                 });

             });
         },

         // 设置'产品详情','服务售后','闪赔规则'
         SetServeSwiper: function (NavName) {
             var oServeSwiperBox = null;
             var oServeSwiper = $('.js_serveSwiper');
             var oSildeNavUl = $('.js_sildeNavUl');
             var oGoodsServerIntor = $('.js_goodsServerIntor')

             // var NavName = ['产品详情','服务售后','闪赔规则'];
             oServeSwiperBox = oServeSwiper.swiper({
                 pagination: oSildeNavUl[0],
                 paginationClickable: true,
                 observer: true,
                 observeParents: true,
                 onInit: function (swiper) {
                     var index = swiper.activeIndex;
                     oGoodsServerIntor.hide().eq(index).show().css({'height': 'auto'});
                 },
                 paginationBulletRender:function(index,className){
                     //添加导航
                     return '<li class="Bflex1 '+className+'">'+ NavName[index] +'</li>';
                 },
                 onSlideChangeEnd: function (swiper) {
                     var index = swiper.activeIndex;
                     var getHeight = oGoodsServerIntor.eq(index).outerHeight(true);

                     oGoodsServerIntor.hide().eq(index).show().css({'height': 'auto'});

                     oWrap.stop().animate({scrollTop: oSildeNavUl_Top}, 10);
                     myPub.JudgeAppHide(function () {
                         //ios
                         window.webkit.messageHandlers.AppModel.postMessage({body: getHeight});
                     });
                 }
             });
         },

         // 评价图片大小调整
         ChangImgSize: function () {
             var oEstimateListLiW = oEstimateList.find('.showImg').width()*0.23;

             oEstimateList.find('li').css({
                 'height': oEstimateListLiW,
                 'width' : oEstimateListLiW
             });

         },

         // 送礼提示显示
         GiftTipShow: function () {
             var _this = this;
             if(oGift_tip.length < 1) return;
             var ss = _this.cutTimeToday();
             showGiftTipOff = myPub.getCookie('showGiftTip');
             if (showGiftTipOff !== 'true') {
                 myPub.setCookie('showGiftTip', 'true', 's'+ss);
                 oGift_tip.show().stop().animate({
                     'top': -3.2+'rem',
                     'z-index': 10
                 },1000);

                 setTimeout(function() {
                     oGift_tip.stop().animate({
                         opacity: 0
                     }, 1000, function() {
                         oGift_tip.hide().css({
                             top: 0,
                             "z-index": -1,
                             opacity: 1
                         });
                     });
                 }, 4000);
             }
         },

         // 当天倒计时
         cutTimeToday: function () {
             var date = new Date();
             date.setMilliseconds(0);

             var nowDate = date.getTime();
             date.setHours(0);
             date.setMinutes(0);
             date.setSeconds(0);
             date.setDate(date.getDate() + 1);
             var nextDay = date.getTime();
             var diffTime = (nextDay - nowDate) / 1000;
             return diffTime
         },

         // 包装展示区轮播
         adsPackSwiper:function () {
             var _this = this;
             _this.packingSwiper = new Swiper('.js_adsPacking',{
                 // freeMode: true,
                 freeModeMomentumRatio: 1,
                 freeModeMomentumVelocityRatio: 1,
                 freeModeMomentumBounce: false,
                 freeModeSticky: true,
                 lazyLoading: true,
                 watchSlidesProgress: true,
                 watchSlidesVisibility : true,
                 // slidesPerView : 'auto',
                 pagination:oPaginPacking,
                 slidesPerView:1
             })
         },

         // 判断是进入海外店铺还是进入普通店铺的接口
         goToStoreDetail: function (supplierId) {
             var _this = this;
             G_JSON_POST(storeDetailUrl,{'supplierId':supplierId},function (data) {
                 var _data = data.data;
                 var _ret = data.ret;
                 // console.log('data',_data,_ret);
                 if(_ret.code=='0'){
                     if(_data){
                         // 海外馆商家
                         window.location.href =  base +'/h/store/storehome?supplierId='+ supplierId ;
                     }
                     else{
                         // 普通商家
                         window.location.href =  base +'/h/store/normalStore/'+ supplierId ;
                     }
                 }
                 else{
                     // 如果请求不到就跳转普通商家
                     window.location.href =  base +'/h/store/normalStore/'+ supplierId ;
                 }
             })
         },
     }

     // 点击进入店铺页面
    $('.js_goToStore').hammer().on('tap', function () {
        var supplierId = $(this).attr('data-supplierId');
        sfddjgooddetail.goToStoreDetail(supplierId);
    });


    function scrollViewGoods() {
        ddjAction.viewGoods(oGoodsHScroll, 0)
    }
    /*
    // 回到过顶部
    oGoTop.hammer().on('tap',function() {
        myPub.OffMuiEvent(false);
        clearTimeout(time_Scroll);
        time_Scroll = setTimeout(function () {
            oWrap.stop().animate({scrollTop: '0'}, 250);
            myPub.OffMuiEvent(true);
        }, 300);
        myPub.HamstopPropaga();
    });
    */

    var textureHeight = otextureMain.outerHeight(true);
    otextureMain.css({'bottom': -textureHeight });
    //显示口感评价信息
    otexture.hammer().on('tap',function(e) {
        myPub.OffMuiEvent(false);
        otextureMain.show().stop().animate({ 'bottom':0 },300,function() {
            oShadow.show();
        });
        myPub.HamstopPropaga();
        //$(document).on('touchmove',function(e) { e.preventDefault();});
    });
    //口感评价按钮
    otextureButton.hammer().on('tap',function(e) {
        otextureMain.stop().animate({bottom:-textureHeight},300,function(){
            otextureMain.hide();
            oShadow.hide();
            myPub.OffMuiEvent(true);
        });
        $(document).off('touchmove');
        myPub.HamstopPropaga()
    });


    var ServerHeight = oServerMain.outerHeight(true);
    oServerMain.css({'bottom': -ServerHeight });

    //显示产品服务信息
    oServerList.hammer().on('tap',function(e) {
        myPub.OffMuiEvent(false);
        oServerMain.show().stop().animate({ 'bottom':0 },300,function() {
            oShadow.show();
        });
        myPub.HamstopPropaga();
        //$(document).on('touchmove',function(e) { e.preventDefault();});
    });

    //产品服务确定按钮
    oServer_button.hammer().on('tap',function(e) {
        oServerMain.stop().animate({bottom:-ServerHeight},300,function(){
            oServerMain.hide();
            oShadow.hide();
            myPub.OffMuiEvent(true);
        });
        $(document).off('touchmove');
        myPub.HamstopPropaga()
    });


    var tasteHeight = otasteMain.outerHeight(true);
    otasteMain.css({'bottom': -tasteHeight });
    //显示试吃服务信息
    otastelist.hammer().on('tap',function(e) {
        myPub.OffMuiEvent(false);
        otasteMain.show().stop().animate({ 'bottom':0 },300,function() {
            oShadow.show();
        });
        myPub.HamstopPropaga();
        //$(document).on('touchmove',function(e) { e.preventDefault();});
    });
    //产品试吃服务确定按钮
    otasteButton.hammer().on('tap',function(e) {
        otasteMain.stop().animate({bottom:-otasteMain},300,function(){
            otasteMain.hide();
            oShadow.hide();
            myPub.OffMuiEvent(true);
        });
        $(document).off('touchmove');
        myPub.HamstopPropaga()
    });


    var sellHeight = osellMain.outerHeight(true);
    osellMain.css({'bottom': -sellHeight });
    //平台卖点服务信息显示
    oselllist.hammer().on('tap',function(e) {
        myPub.OffMuiEvent(false);
        osellMain.show().stop().animate({ 'bottom':0 },300,function() {
            oShadow.show();
        });
        myPub.HamstopPropaga();
        //$(document).on('touchmove',function(e) { e.preventDefault();});
    });
    //平台卖点确定按钮
    osellButton.hammer().on('tap',function(e) {
        osellMain.stop().animate({bottom:-sellHeight},300,function(){
            osellMain.hide();
            oShadow.hide();
            myPub.OffMuiEvent(true);
        });
        $(document).off('touchmove');
        myPub.HamstopPropaga()
    });

    // 弹出商家信息列表
    oContactBossBtn.on('click',function() {
        var styleTitle = 'width:100%;  border:none';
        var _sBossInfo= $('.js_bossInfo');
        var _index = oBossInfo.index(_sBossInfo);
        var _BossName = oBossName.eq(_index).text();
        _sBossInfo.show();
        myPub.TipTitleLayer('联系商家: '+_BossName,styleTitle, _sBossInfo.html(),function() {
            _sBossInfo.hide();
        });
    });



   /* // 阴影关闭
    oShadow.hammer().on('tap',function(e) {
        //隐藏服务
        oServerMain.stop().animate({bottom:-moveHeight},300,function(){
            oServerMain.hide();
            oShadow.hide();
        });
        myPub.OffMuiEvent(true);
        myPub.HamstopPropaga();
        $(document).off('touchmove');
    });*/
    // 阴影点击关闭
    oShadow.hammer().on('tap', function () {
        var bSideOff = true;
        //隐藏服务
        otextureMain.stop().animate({bottom:-textureHeight},300,function(){
            otextureMain.hide();
            oShadow.hide();
            bSideOff = true
        });
        myPub.HamstopPropaga();
        if(typeof mui !== 'undefined'){
            myPub.OffMuiEvent(true);
        }

    });

    // 阴影点击关闭
    oShadow.hammer().on('tap', function () {
        var bSideOff = true;
        //隐藏服务
        oServerMain.stop().animate({bottom:-ServerHeight},300,function(){
            oServerMain.hide();
            oShadow.hide();
            bSideOff = true
        });
        myPub.HamstopPropaga();
        if(typeof mui !== 'undefined'){
            myPub.OffMuiEvent(true);
        }

    });
    // 阴影点击关闭
    oShadow.hammer().on('tap', function () {
        var bSideOff = true;
        //隐藏试吃
        otasteMain.stop().animate({bottom:-tasteHeight},300,function(){
            otasteMain.hide();
            oShadow.hide();
            bSideOff = true
        });
        myPub.HamstopPropaga();
        if(typeof mui !== 'undefined'){
            myPub.OffMuiEvent(true);
        }

    });

    // 阴影点击关闭
    oShadow.hammer().on('tap', function () {
        var bSideOff = true;
        //隐藏服务
        osellMain.stop().animate({bottom:-sellHeight},300,function(){
            osellMain.hide();
            oShadow.hide();
            bSideOff = true
        });
        myPub.HamstopPropaga();
        if(typeof mui !== 'undefined'){
            myPub.OffMuiEvent(true);
        }

    });


    // 送TA 按钮
    // oGiftSendBtn.hammer().on('tap',function(e) {
    //     oShadow.show();
    //     oGiftSend_TypeSelet.show();
    //     oTypeSeletList.show();
    //     oTypeSeletIntro_layer.hide();
    //     myPub.HamstopPropaga();
    // });

    // 送礼弹层关闭按钮
    oTypeSelelt_close.on('click',function(e) {
        oShadow.hide();
        oGiftSend_TypeSelet.hide();
        oTypeSeletList.show();
        oTypeSeletIntro_layer.hide();
        e.stopPropagation();
    });

    oTypeSelet_intro.on('click',function(e) {
        oTypeSeletList.hide();
        oTypeSeletIntro_layer.show();
        e.stopPropagation();
    });

    // 送礼提示关闭
    oClose_giftTip.on('click', function (e) {
        oGift_tip.stop().animate({
            'opacity': 0
        },1000, function () {
            oGift_tip.hide().css({
                'top': 0,
                'z-index': -1,
                'opacity': 1
            });
        });
        e.stopPropagation();
    });

    // 消息集合框
    var oIconList = $('.js_IconList');
    var oIconBtn = $('.js_IconBtn');


    oIconBtn.on('click', function (e) {
        if(oIconBtn.hasClass('on')) {
            oIconBtn.removeClass('on');
            IconListShow (false);
        }
        else {
            oIconBtn.addClass('on');
            IconListShow (true);
        }
        e.stopPropagation();
    })


    // 消息和功能点的展示和消失
    function IconListShow (off) {
        if(off) {
            oIconList.show().stop().animate({
                'opacity': 1
            },500);
        }
        else {
            oIconList.stop().animate({
                'opacity': 0
            },500, function () {
                oIconList.hide();
            });
        }
    }


    // 限时秒杀
    var oTimeLimitSale = $('.js_timeLimt_sale');        // 限时秒杀
    var oLimitProLess = $('.js_limt_proLess');          // 进度不足90%
    var oLimitProMore = $('.js_limt_proMore');          // 进度大于90%
    var oLimitLessBar = $('.js_limitLessBar');          // 进度不足90%进度条
    var oLimitMoreBar = $('.js_LimitMoreBar');          // 进度大于90%进度条
    var oLimitPrecent = $('.js_limitPrecent');          // 进度小于90%百分比
    var nstockNum = $('.js_timeLimt_progress').attr('stockNum')*1;    // 总的库存
    var nsalekNum = $('.js_timeLimt_progress').attr('salekNum')*1;    // 销售数量
    var endTime = $('.js_timeLimt_progress').attr('endDate');    // 结束时间
    var nowTime = $('.js_timeLimt_progress').attr('nowDate');    // 现在时间
    var nsalePrencent = nsalekNum/nstockNum;
    var time_CutTime;
    var nowDate = new Date(getMyDate(nowTime));
    var now = nowDate.getTime();
    var limitTimeSale = {
        // 限时秒杀倒计时
        CutDataTime : function () {
            var _this = this;

            var endDate = new Date(getMyDate(endTime));//设置截止时间
            var end = endDate.getTime();
            var leftTime = end - now; //时间差
            var hh, mm, ss, ms;
            if(leftTime >= 0) {
                hh = Math.floor(leftTime / 1000 / 60 / 60 % 24);
                mm = Math.floor(leftTime / 1000 / 60 % 60);
                ss = Math.floor(leftTime / 1000 % 60);
                var mstring = leftTime % 1000+'';
                ms = Number(mstring.substring(0,2));

                ss = ss < 10 ? ('0' + ss) : ss;
                mm = mm < 10 ? ('0' + mm) : mm;
                hh = hh < 10 ? ('0' + hh) : hh;
                ms = ms < 10 ? ('0' + ms) : ms;
            }else{
                //console.log('已截止!')
            }
            $('.js_countDownHour').text(hh);
            $('.js_countDownMinute').text(mm);
            $('.js_countDownSecond').text(ss);
            $('.js_countDownHourMS').text(ms);

            clearTimeout(time_CutTime);
            time_CutTime = setTimeout(function () {
                now += 50;
                _this.CutDataTime()
            }, 50);
        },

        // 限时秒杀进度条
        ProgressBar : function () {
            if(oTimeLimitSale && oTimeLimitSale.length > 0){
                var  precent=Math.floor(nsalePrencent*100);
                if(nsalePrencent < 0.9){
                    oLimitProLess.show();
                    oLimitProMore.hide();
                    oLimitLessBar.css({
                        'width' : precent + '%'
                    });
                    oLimitPrecent.text(precent + '%')
                }else if(nsalePrencent >= 0.9 && nsalePrencent <1){
                    oLimitProLess.hide();
                    oLimitProMore.show();
                    oLimitMoreBar.css({
                        'width' : precent + "%"
                    })
                }
            }
        },


    }
    //  兼容ios中间过度
      function getMyDate(date){
        //var nTimeindex = date.indexOf('.');
        if(date){
            var newDate = date.replace(/-/g,"/");
            return newDate
        }
    }

    // 用户行为
    var ddjAction = {
        viewData: [],
        cout: 0,
        loadingTime: null,
        viewGoods: function (obj, iNow) {
            var _this = this;
            // 首页和分类区分
            var ddjActionPositionId = {};
            ddjActionPositionId.positionFirst = '物品详情';
            ddjActionPositionId.positionId = 1;
            ddjActionPositionId.positionSecond = '推荐';

            // 统计曝光数据
            visualArea.viewEl.showViewEls( obj, function (data, dataJson) {
                _this.checkDdjhoc(function () {
                    ddjhoc.setData(data, 'rec_show', 'add', function () {
                        console.log('ddjhoc.params.rec_show.goodsdetail', ddjhoc.params);
                        if( ddjhoc.params.length != 0 ) ddjhoc.sendData( ddjhoc.params );

                        // console.log('ddjhoc.ddjParams.rec_show.index', ddjhoc.ddjParams);
                        // if( ddjhoc.ddjParams.length != 0 ) ddjhoc.sendDDJData( ddjhoc.ddjParams );

                    }, dataJson, ddjActionPositionId);
                });

            });
        },

        checkDdjhoc: function (fn) {
            var _this = this;
            // console.log( typeof ddjhoc )
            if( typeof ddjhoc == 'undefined' ) {
                if(_this.cout > 6) {
                    clearTimeout(_this.loadingTime);
                    // console.log( typeof ddjhoc )
                    if(fn) fn();
                }
                else {
                    _this.cout++;
                    _this.loadingTime = setTimeout(function() {
                        // console.log(_this.cout)
                        _this.checkDdjhoc(fn);
                    }, 1000)
                }
            }
            else {
                clearTimeout(_this.loadingTime);
                // console.log( typeof ddjhoc )
                if(fn)fn();
            }
        }
    }

});